/**
 * @description 订单数据操作
 */
const Order = require('../../models/Order')
const Address = require('../../models/Address')
const Product = require('../../models/Product')
!(async () => {
  //创建订单
  const requestBody = {
    addressId: '60951a7447446964c02fd059',
    shopId: '6095f02a6c8bc6187445a480',
    shopName: '沃尔玛',
    isCanceled: false,
    products: [
      {
        id: '6095f81430defc5ef8ead6df',
        num: 3
      },
      {
        id: '6095f81430defc5ef8ead6de',
        num: 5
      }
    ]
  }
  //获取address
  const address=await Address.findById(requestBody.addressId);
  // console.log(address);
  //获取商品列表
  const pIds=requestBody.products.map(p=>p.id)
  const productList=await Product.find({
    shopId:requestBody.shopId,
    _id:{$in:pIds}
  })
  console.log(pIds);
  console.log(productList);
  //整合订单购买数量
  const productListWithSales=productList.map(p=>{
    //商品id
    const id=p._id.toString()
    //找到商品销量
    const filterProducts=requestBody.products.filter(item=>item.id===id)
    // console.log(filterProducts);
    if(filterProducts.length===0){
      //没有找到匹配的数量，报错
      throw new Error('未找到匹配的销售数据')
    }
    return{
      product:p,
      orderSales:filterProducts[0].num
    }
  })
  // console.log(productNum);
  /* await Order.create({
    username:'zhansan',
    address:address,
    shopId:requestBody.shopId,
    shopName:requestBody.shopName,
    isCanceled: false, // 是否被取消，依赖于前端的传入
    products: productListWithSales
  }) */
   // 获取订单列表
   /* const orderList = await Order.find().sort({ _id: -1 }) // 逆序
   console.log('order list', orderList)
   console.log('order product 0', orderList[0].products[0]) */
})()